﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using UFC.DBUtility;
using Newtonsoft.Json;
using UFC.Common;
using System.Net;
using System.Collections;
using Newtonsoft.Json.Converters;
using System.IO;
using System.Configuration;
using System.Threading.Tasks;
using System.Web;

namespace SendIndustrialNetwork
{
    public class SendMESDataToWMS
    {
        public string dataCenterHost = ConfigurationManager.AppSettings["dataCenterHost"].ToString();
        public string fromAppId = ConfigurationManager.AppSettings["ToDataCenterAppID"].ToString();//推送数据中心来源ID
        public string toAppId_WMS = ConfigurationManager.AppSettings["ToAppID_WMS"].ToString();//推送数据中心目的ID（WMS）
        public string fileUploadUrl = "http://{0}:8080/lygkdc-service/lygk/dc/fileUploaddc";//文件上传地址
        public SendMESDataToWMS()
        {
            //fileUploadUrl = string.Format(fileUploadUrl, dataCenterHost);//文件上传地址
            fileUploadUrl = "http://localhost/LYMesApi/api/Default/fileUpload2";
            LogHelp.SetConfig();
        }

        //表数据上传
        public void Excute()
        {
            SendMesDataToWMS();
        }

        /// <summary>
        /// 推送类型
        /// </summary>
        private enum WmsType
        {
            入库申请,
            领料单下发,
            入库撤销,
            领料单撤销,
            转工物料配送,
            转工物料配送撤销,
            转工物料配送完成,
            返件申请,
            退料退库申请,
            配套单下发,
            配套单撤销
        }

        /// <summary>
        /// 通用推送数据 add by zhangrj 20250918
        /// </summary>
        void SendMesDataToWMS()
        {
            Array wmsList = Enum.GetValues(typeof(WmsType)); //获取所有的推送类型
            ParallelOptions parallelOption = new ParallelOptions();
            parallelOption.MaxDegreeOfParallelism = Environment.ProcessorCount / 2;
            LogHelp.WriteLog(string.Format("开始推送WMS，总的推送接口数：{0}，并行数：{1}", wmsList.Length, parallelOption.MaxDegreeOfParallelism));
            /*并行推送，（注：如果要调试，可注释掉WmsType中的不调试的类型进行单个调试）*/
            Parallel.For(0, wmsList.Length, parallelOption, i =>
            {
                string wmsTypeName = Enum.GetName(typeof(WmsType), wmsList.GetValue(i));
                var strSql = string.Format(@"SELECT t.id,t.json,t.methodname,t.toappid FROM sync_sendto_wms t WHERE t.ismeshandle = 0 AND t.methodname = '{0}'", wmsTypeName);
                DataTable dtSendData = OracleHelper.QueryTable(strSql, null);
                foreach (DataRow row in dtSendData.Rows)
                {
                    try
                    {
                        string json = row["json"].ToString();
                        Dictionary<string, object> dict = JsonConvert.DeserializeObject<Dictionary<string, object>>(json);
                        string absolutePath = AppDomain.CurrentDomain.BaseDirectory + "files\\";
                        if (!Directory.Exists(absolutePath))
                        {
                            Directory.CreateDirectory(absolutePath);
                        }
                        string filename = string.Format("{0}.json", row["id"].ToString());
                        string filePath = absolutePath + filename;
                        File.WriteAllText(filePath, json, new UTF8Encoding(false));
                        /*设置推送头部参数*/
                        HeadEntity head = GetHeadEntity((WmsType)wmsList.GetValue(i), dict);
                        head.FileName = filePath;
                        /*开始推送*/
                        LogHelp.WriteLog(string.Format("【{0}接口】开始上传文件【{1}】", wmsTypeName, filename));
                        var result = HttpUtils.uploadFile(fileUploadUrl, head);
                        /*推送返回结果处理*/
                        LogHelp.WriteLog(string.Format("【{0}接口】文件上传返回结果：{1}", wmsTypeName, result));
                        Dictionary<string, string> resDic = JsonConvert.DeserializeObject<Dictionary<string, string>>(result);
                        string updateSql = @"update sync_sendto_wms set ISMESHANDLE = 1,businessid = '{0}',sendtime = SYSDATE where ID = '{1}'";
                        updateSql = string.Format(updateSql, resDic["result"].ToString(), row["id"].ToString());
                        OracleHelper.ExecuteSql(updateSql);
                        /*删除推送数据*/
                        if (File.Exists(filePath))
                        {
                            File.Delete(filePath);
                        }
                    }
                    catch (Exception ex)
                    {
                        LogHelp.WriteLog(string.Format("【WMS】推送MES{0}给数据中心异常：{1}", wmsTypeName, ex.Message));
                    }
                }
            });
        }

        /// <summary>
        /// 获取推送表头参数 add by zhangrj 20250918
        /// </summary>
        /// <param name="wmsType"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        HeadEntity GetHeadEntity(WmsType wmsType, Dictionary<string, object> param)
        {
            HeadEntity head = new HeadEntity();
            head.Formappid = fromAppId;//来源appid
            head.Toappid = toAppId_WMS;//目标appid
            switch (wmsType)
            {
                case WmsType.入库申请:
                    head.Bstype = "MES_PRODUCT_INBOUND";
                    head.BsData = param["bizDataNo"].ToString();//订单号
                    break;
                case WmsType.领料单下发:
                    head.Bstype = "MES_MATERIAL_REQ_INBOUND";
                    head.BsData = param["bizDataNo"].ToString();//订单号
                    break;
                case WmsType.入库撤销:
                    head.Bstype = "MES_INBOUND_CANCEL";
                    head.BsData = param["bizDataNo"].ToString();//订单号
                    break;
                case WmsType.领料单撤销:
                    head.Bstype = "MES_KIT_PICK_CANCEL";
                    head.BsData = param["bizDataNo"].ToString();//订单号
                    break;
                case WmsType.转工物料配送:
                    head.Bstype = "MES_PRODUCTION_TASK_TRANSFER_DISPATCH";
                    head.BsData = param["bizDataNo"].ToString();//订单号
                    break;
                case WmsType.转工物料配送撤销:
                    head.Bstype = "MES_PRODUCTION_TASK_REJECT";
                    head.BsData = param["bizDataNo"].ToString();//订单号
                    break;
                case WmsType.转工物料配送完成:
                    head.Bstype = "MES_PRODUCTION_TASK_TRANSFER_DISPATCH";
                    head.BsData = param["bizDataNo"].ToString();//订单号
                    break;
                case WmsType.返件申请:
                    head.Bstype = "MES_RETURN_APPLY";
                    head.BsData = param["bizDataNo"].ToString();//订单号
                    break;
                case WmsType.退料退库申请:
                    head.Bstype = "MES_RETURN_INBOUND";
                    head.BsData = param["bizDataNo"].ToString();//订单号
                    break;
                case WmsType.配套单下发:
                    head.Bstype = "MES_KITTING_LIST_INBOUND";
                    head.BsData = param["bizDataNo"].ToString();//订单号
                    break;
                case WmsType.配套单撤销:
                    head.Bstype = "MES_KIT_PICK_CANCEL";
                    head.BsData = param["bizDataNo"].ToString();//订单号
                    break;
                default:
                    break;
            }
            head.WenJianQiCaoRen = "刘美美";
            head.QianFaRen = "刘美美";
            head.ShenPiRen = "刘美美";
            return head;
        }
    }
}